import { SERVICES } from '@/common';
import { Avatar, Button, Upload, UploadProps, message } from 'antd';
import React from 'react';
import './index.less';
export interface IAvatarProps {
	onChange: (file: any) => void;
	[key: string]: any;
}

const AvatarCom: React.FC<IAvatarProps> = ({ value, onChange }) => {
	const [avatarUrl, setAvatarUrl] = React.useState<string>(value);

	React.useEffect(() => {
		setAvatarUrl(value);
	}, [value]);

	const props: UploadProps = {
		name: 'file',
		action: '/api/upload/doAdd',
		maxCount: 1,
		headers: {
			authorization: 'Bearer ' + localStorage.getItem('vehicle_token') || '',
		},
		onChange(info) {
			if (info.file.status !== 'uploading') {
				console.log(info.file, info.fileList);
			}
			if (info.file.status === 'done') {
				message.success(`文件上传成功`);
				setAvatarUrl(info.file.response.data.url || '');
				onChange(info.file.response.data.url);
			} else if (info.file.status === 'error') {
				message.error(`${info.file.name} 文件上传失败`);
			}
		},
	};
	return (
		<div
			style={{
				display: 'flex',
				justifyContent: 'center',
				flexDirection: 'column',
				alignItems: 'center',
			}}
		>
			<Avatar size={200} src={SERVICES + avatarUrl} alt="头像" />

			<div style={{ marginTop: '10px' }}>
				<Upload {...props}>
					<Button>点击更改头像</Button>
				</Upload>
			</div>
		</div>
	);
};

export default AvatarCom;
